<template>
  <div class="search">
    <van-nav-bar
      fixed
      title="搜索中心"
      left-arrow
      @click-left="$router.back()"
    />
    <van-search
      v-model.trim="value"
      show-action
      shape="round"
      placeholder="请输入搜索关键词"
      @search="onSearch(value)"
      @input="searchFn"
    >
      <template #action>
        <div @click="onSearch(value)">搜索</div>
      </template>
    </van-search>
    <!-- 搜索的内容和历史记录 -->
    <van-cell-group v-if="value">
      <van-cell
        icon="search"
        v-for="item in list"
        :key="item"
        @click="onSearch(item)"
      >
        <!-- <van-cell title="单元格" icon="search" /> -->
        <span v-html="highLight(item, value)"></span>
      </van-cell>
    </van-cell-group>

    <!-- 历史记录 -->
    <van-cell-group v-else>
      <van-cell title="历史记录" />
      <van-cell
        :title="item"
        v-for="item in historyList"
        :key="item"
        @click="onSearch(item)"
      >
        <template #right-icon>
          <van-icon name="cross" @click="del(item)" />
        </template>
      </van-cell>
    </van-cell-group>
  </div>
</template>

<script>
import { getSuggest } from '@/api/search'
import { setHistory, getHistory } from '@/utils/storage'
export default {
  name: 'Search',
  data() {
    return {
      value: '',
      list: [],
      historyList: getHistory()
    }
  },
  methods: {
    highLight(str, keyword) {
      return str.replace(
        new RegExp(keyword, 'gi'),
        item => `<span style="color:red">${item}</span>`
      )
    },
    onSearch(value) {
      if (!value) {
        return this.$toast('请输入搜索内容')
      }
      console.log('正在搜索...', value)
      this.historyList = this.historyList.filter(item => item !== value)
      this.historyList.unshift(value)
      // 把历史记录存储到本地
      setHistory(this.historyList)
      // 跳转到搜索结果页面 并传递搜索的关键字
      this.$router.push({
        path: '/search/result',
        query: {
          keyword: value
        }
      })
    },
    // search 输入框搜索

    searchFn() {
      // 防抖
      clearTimeout(this.timerId)
      this.timerId = setTimeout(async () => {
        if (!this.value) {
          return
        }
        const res = await getSuggest(this.value)
        // console.log(res)
        this.list = res.data.options
      }, 300)
    },

    // 删除历史记录
    del(value) {
      this.historyList = this.historyList.filter(item => item !== value)
      setHistory(this.historyList)
    }
  }
}
</script>

<style lang="less" scoped>
.search {
  padding-top: 50px;
}
</style>
